<?php
require_once 'Translator/Model.php';

/**
 * Model for translation applications.
 */
class ApplicationModel extends Translator_Model {
	/**
	 * Create application for the user
	 * 
	 * @param int $userid
	 * @param string $languages
	 * @param string $qualification
	 */
	public function apply($userid, $languages, $qualification) {
		// create application
		$this->_db->insert('applications', array(
			'user' => intval($userid),
			'languages' => $languages,
			'qualification' => $qualification,
			'time' => time()
		));
		
		$insertid = $this->_db->lastInsertId();
		
		// update user dataset to indicate that he applied
		$this->_db->update('users', array(
			'request' => 1
		), 'id = '.intval($userid));
		
		return $insertid;
	}
	
	/**
	 * Fetch applications.
	 */
	public function fetchApplications() {
		return $this->_db->fetchAll(
			'SELECT apps.id, apps.time, users.name
			 FROM applications AS apps
			 LEFT JOIN users ON(users.id = apps.user)
			 ORDER BY time ASC');
	}
	
	public function fetchApplication($id) {
		return $this->_db->fetchRow(
			'SELECT apps.*, users.name, users.email
			 FROM applications AS apps
			 LEFT JOIN users ON(users.id = apps.user)
			 WHERE apps.id = ?
			 LIMIT 1',
		array($id));
	}
	
	/**
	 * Remove application, is called as soon as the application is no
	 * longer necessary (accepted or declined).
	 * 
	 * @param int $id application id
	 * @param int $userid application requester id
	 * @param boolean $accepted true if application was accepted, false otherwise
	 */
	public function removeApplication($id, $userid, $accepted) {
		$this->_db->delete('applications', 'id = '.intval($id));
		
		$this->_db->update('users', array(
			'request' => 0,
			'group' => ($accepted ? 2 : 1)
		), 'id = '.intval($userid));
	}
}